package com.banciyuan.bcywebview.biz.main.group.focused;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.GroupApi;
import com.banciyuan.bcywebview.base.fragment.BaseLazyContainerFragment;
import com.banciyuan.bcywebview.base.helper.LoadingHelper;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshBase;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshListView;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.OnErrorProxy;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import de.greenrobot.daoexample.model.SimpleTeam;

/**
 * Created by hy on 2016/4/7.
 */
public class FocusedGroupFragment extends BaseLazyContainerFragment {
    private PullToRefreshListView mRefreshListView;
    private ListView mListView;
    private RequestQueue queue;
    private LoadingHelper mProgressbarHelper;
    private int page = 1;
    private boolean loading = false;
    private boolean is_end = true;
    private FocusedGroupAdapter mAdapter;
    private List<SimpleTeam> simpleTeams = new ArrayList<>();

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.newgrouppost_layout, null);
        initArgs();
        initProgressbar(rootView);
        initUi(rootView);
        initAction();
        initData();
        return rootView;
    }

    @Override
    protected void initArgs() {
        queue = VolleyQueue.getRquest(getActivity());
    }

    @Override
    protected void initProgressbar(View rootview) {
        mProgressbarHelper = new LoadingHelper(rootview);
        mProgressbarHelper.setActionCallbacks(new LoadingHelper.OnProgressCallbacks() {
            @Override
            public void onActionClick(int id) {
                mProgressbarHelper.onLoading();
                initData();
            }
        });
        mProgressbarHelper.onLoading();
    }

    @Override
    protected void initUi(View rootview) {
        mRefreshListView = (PullToRefreshListView) rootview.findViewById(R.id.listview);
        mListView = mRefreshListView.getRefreshableView();
    }

    @Override
    protected void initAction() {
        mRefreshListView.setOnLastItemVisibleListener(new PullToRefreshBase.OnLastItemVisibleListener() {
            @Override
            public void onLastItemVisible() {
                if (!loading && !is_end) {
                    loading = true;
                    page++;
                    initData();
                }
            }
        });
        mRefreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                is_end = false;
                loading = false;
                page = 1;
                initData();
            }
        });
    }

    @Override
    protected void initData() {
        loading = true;
        String url = HttpUtils.BASE_URL + GroupApi.getUserGroup();
        List<BcyPair> paramsList = new ArrayList<>();
        paramsList.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(getActivity()).getToken()));
        paramsList.add(new BcyPair(HttpUtils.INDEX_P, page + ""));
        paramsList.add(new BcyPair(HttpUtils.LIMIT, "20"));
        HashMap<String, String> map = HttpUtils.getData(paramsList);
        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String result) {
                if (StatusCodeUtils.dealStatusCode(result, getActivity())) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        Gson gson = new Gson();
                        List<SimpleTeam> templist = gson.fromJson(jsonObject.getString(HttpUtils.UPLOAD_DATA), new TypeToken<List<SimpleTeam>>() {
                        }.getType());
                        processData(templist);
                    } catch (Exception e) {
                        mRefreshListView.onRefreshComplete();
                        mProgressbarHelper.onFailed();
                        loading = false;
                    }
                } else {
                    mRefreshListView.onRefreshComplete();
                    mProgressbarHelper.onFailed();
                    loading = false;
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                mRefreshListView.onRefreshComplete();
                mProgressbarHelper.onFailed();
                loading = false;
            }
        };

        OnErrorProxy errorProxy = new OnErrorProxy(onError, onSucc, url, getActivity(), map);
        StringRequestParam requestParam = new StringRequestParam(Request.Method.POST, url, map, onSucc, errorProxy);
        queue.add(requestParam);
    }


    private void processData(List<SimpleTeam> tempTeams) {
        if (page == 1) {
            simpleTeams.clear();
        }
        simpleTeams.addAll(tempTeams);
        if (tempTeams.isEmpty()) {
            is_end = true;
        }
        if (null == mAdapter) {
            mAdapter = new FocusedGroupAdapter(getActivity(), simpleTeams);
            mListView.setAdapter(mAdapter);
        } else {
            mAdapter.notifyDataSetChanged();
        }
        loading = false;
        mProgressbarHelper.onSuccess();
        mRefreshListView.onRefreshComplete();
    }

}
